/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
const { Signer } = require('@volcengine/openapi');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');

// 读取.env.local文件
const loadEnvConfig = () => {
  try {
    const envPath = path.resolve(__dirname, '..', '.env.local');
    const envContent = fs.readFileSync(envPath, 'utf-8');
    const envVars = {};

    // 解析.env.local内容
    envContent.split('\n').forEach((line) => {
      // 忽略注释和空行
      if (!line || line.startsWith('#')) return;

      const [key, ...valueParts] = line.split('=');
      const value = valueParts.join('=').trim();
      if (key && value) {
        envVars[key.trim()] = value;
      }
    });

    return envVars;
  } catch (error) {
    console.error('无法读取.env.local文件:', error.message);
    return {};
  }
};

// 加载环境变量
const envConfig = loadEnvConfig();

const app = new Koa();

app.use(
  cors({
    origin: '*',
  })
);

/**
 * @notes 在 https://console.volcengine.com/iam/keymanage/ 获取 AK/SK
 */
const ACCOUNT_INFO = {
  /**
   * @notes 必填, 在 https://console.volcengine.com/iam/keymanage/ 获取
   */
  accessKeyId: envConfig.accessKeyId || 'Your AK',
  /**
   * @notes 必填, 在 https://console.volcengine.com/iam/keymanage/ 获取
   */
  secretKey: envConfig.secretKey || 'Your SK',
  /**
   * @notes 非必填, 主账号无须传入, 子账号须传, 获取方式可参考
   * https://www.volcengine.com/docs/6348/1315561 中的 步骤 4-使用子账号调用智能体接口 一节
   */
  sessionToken: envConfig.sessionToken || '',
};

// 打印 accessKeyId 的前4位字符
console.log('accessKeyId 前4位字符:', ACCOUNT_INFO.accessKeyId.substring(0, 4));
// 打印 secretKey 的前4位字符
console.log('secretKey 前4位字符:', ACCOUNT_INFO.secretKey.substring(0, 4));

app.use(bodyParser());

app.use(async (ctx) => {
  /**
   * @brief 代理 AIGC 的 OpenAPI 请求
   */
  if (ctx.url.startsWith('/proxyAIGCFetch') && ctx.method.toLowerCase() === 'post') {
    const { Action, Version } = ctx.query || {};
    const body = ctx.request.body;

    /**
     * 参考 https://github.com/volcengine/volc-sdk-nodejs 可获取更多 火山 TOP 网关 SDK 的使用方式
     */
    const openApiRequestData = {
      region: 'cn-north-1',
      method: 'POST',
      params: {
        Action,
        Version,
      },
      headers: {
        Host: 'rtc.volcengineapi.com',
        'Content-type': 'application/json',
      },
      body,
    };
    const signer = new Signer(openApiRequestData, 'rtc');
    signer.addAuthorization(ACCOUNT_INFO);

    /** 参考 https://www.volcengine.com/docs/6348/69828 可获取更多 OpenAPI 的信息 */
    const result = await fetch(`https://rtc.volcengineapi.com?Action=${Action}&Version=${Version}`, {
      method: 'POST',
      headers: {
        ...openApiRequestData.headers,
      },
      body: JSON.stringify(body),
    });
    const volcResponse = await result.json();
    ctx.body = volcResponse;
  } 
  /**
   * @brief 提供环境变量给前端应用
   */
  else if (ctx.url === '/env' && ctx.method.toLowerCase() === 'get') {
    // 设置跨域响应头
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Methods', 'GET');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type');
    
    console.log('接收到前端请求环境变量');
    console.log('返回的环境变量信息:');
    console.log('AppId:', envConfig.AppId.substring(0, 10) || '未设置');
    console.log('RoomId:', envConfig.RoomId || '未设置');
    console.log('UserId:', envConfig.UserId || '未设置');
    console.log('Token 状态:', envConfig.Token ? '已设置' + ' (长度: ' + envConfig.Token.length + ', 前10位: ' + envConfig.Token.substring(0, 10) + ', 后10位: ' + envConfig.Token.substring(envConfig.Token.length - 10) + '...)' : '未设置');
    console.log('DOUBAO_PRO_32K:', envConfig.DOUBAO_PRO_32K.substring(0, 10) || '未设置');
    
    // 返回环境变量
    const envVariables = {
      DOUBAO_PRO_32K: envConfig.DOUBAO_PRO_32K || '',
      AppId: envConfig.AppId || '',
      RoomId: envConfig.RoomId || '',
      UserId: envConfig.UserId || '',
      Token: envConfig.Token || '',
      TTSAppId: envConfig.TTSAppId || '',
      TTSToken: envConfig.TTSToken || '',
      ASRAppId: envConfig.ASRAppId || '',
      ASRToken: envConfig.ASRToken || ''
    };
    
    ctx.body = envVariables;
  } else {
    ctx.body = '<h1>404 Not Found</h1>';
  }
});

app.listen(3001, () => {
  console.log('AIGC Server is running at http://localhost:3001');
});
